package cn.wp.common.core.plugin.fileserver;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.wp.common.core.Wp;
import cn.wp.common.core.dto.WpResult;
import cn.wp.common.core.exception.WpException;
import cn.wp.common.core.util.ResponseUtil;
import cn.wp.common.core.web.annotation.ClearInterceptor;
import cn.wp.common.core.web.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 文件上传服务
 */
@Controller
@RequestMapping(value = Wp.WebCommonBase + "/file")
@ClearInterceptor(LoginInterceptor.class)
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 上传
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public WpResult upload(HttpServletRequest request,String value){
        // 文件上传
        List<FileInfo> list = CollectionUtil.newArrayList();
        try {
            if(request instanceof AbstractMultipartHttpServletRequest){
                //CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getServletContext());
                StandardMultipartHttpServletRequest multipartHttpServletRequest = (StandardMultipartHttpServletRequest)request;
                Map<String,MultipartFile> multipartFileMap = multipartHttpServletRequest.getFileMap();

                for (Map.Entry<String,MultipartFile> entry: multipartFileMap.entrySet()) {
                    MultipartFile multipartFile = entry.getValue();
                    String fileName = multipartFile.getOriginalFilename();
                    FileInfo fileInfo = fileService.upload(multipartFile.getInputStream(),new StrategyParameter(fileName,value),null);
                    list.add(fileInfo);
                }
            }
        } catch (IOException e) {
            throw new WpException("文件上传出错",e);
        }

        return new WpResult().success(list);
    }

    /**
     * 下载
     * @param path
     * @return
     */
    @PostMapping("/download")
    public WpResult download(HttpServletResponse response,String path){
        String fullStorePath = FileServerHelper.getFullStorePath(path);
        ResponseUtil.writeFile(response,new File(fullStorePath));
        return new WpResult().success();
    }

}